//
// Created by hamlet on 2022/1/11.
//

#include "mainprocess.h"
#include <QCoreApplication>
#include <QGuiApplication>
#include <QToolButton>
#include <QMenu>
#include <QPainter>
#include <QSvgRenderer>
#include "mainwindow.h"
#include "settingswidget.h"
#include "tianqiaccesser.h"

MainProcess::MainProcess(QObject *parent) :
        m_tianqiAccesser(new TianqiAccesser(this)),
        m_mainWindow(nullptr) {
    QIcon::setFallbackSearchPaths(QIcon::fallbackSearchPaths() << ":/sys-icon");

    m_refreshAction = new QAction(tr("刷新"), this);
    m_settingsShowAction = new QAction(tr("设置"), this);
    m_showAction = new QAction(tr("显示"), this);
    m_quitAction = new QAction(tr("退出"), this);
    m_refreshAction->setIcon(QIcon::fromTheme("view-refresh"));
    m_settingsShowAction->setIcon(QIcon::fromTheme("preferences-other"));
    m_showAction->setIcon(QIcon::fromTheme("show_table_column"));
    m_quitAction->setIcon(QIcon::fromTheme("application-exit"));
    connect(m_refreshAction, &QAction::triggered, m_tianqiAccesser, &TianqiAccesser::requestDataAndCache);
    connect(m_settingsShowAction, &QAction::triggered, this, &MainProcess::showSettingsDialog);
    connect(m_showAction, &QAction::triggered, this, &MainProcess::showMainWindow);
    connect(m_quitAction, &QAction::triggered, qApp, &QCoreApplication::quit);

    m_trayIconMenu = new QMenu();
    m_trayIconMenu->addAction(m_refreshAction);
    m_trayIconMenu->addAction(m_settingsShowAction);
    m_trayIconMenu->addSeparator();
    m_trayIconMenu->addAction(m_showAction);
    m_trayIconMenu->addSeparator();
    m_trayIconMenu->addAction(m_quitAction);

    m_trayIcon = new QSystemTrayIcon(this);
    m_trayIcon->setContextMenu(m_trayIconMenu);
    m_trayIcon->show();
    connect(m_trayIcon, &QSystemTrayIcon::activated, this, &MainProcess::iconActivated);

    connect(m_tianqiAccesser, &TianqiAccesser::sign_needUpdate, this, &MainProcess::updatePage);
    connect(m_tianqiAccesser, &TianqiAccesser::sign_freeMemory, this, &MainProcess::freeMemory);

    m_tianqiAccesser->requestData();
}

MainProcess::~MainProcess() {
    freeMemory();
    delete m_trayIconMenu;
}

void MainProcess::updatePage() {
    const auto &data = m_tianqiAccesser->getData();

    m_trayIcon->setToolTip(tr("%1\342\204\203，%2").arg(data.temp).arg(data.category));

    // QPainter也是，QSvgRenderer也是，都不太懂，太差了！
    auto iconFile = QString("/usr/share/tianqi/icons/%1.svg").arg(data.icon);
    QSvgRenderer renderer{iconFile};
    QPixmap pixmap{QSize{64, 64}};
    pixmap.fill(Qt::transparent);
    QPainter painter;
    painter.begin(&pixmap);
    renderer.render(&painter);
    painter.end();
    QImage tmp = pixmap.toImage();
    for (int i = 0; i < tmp.width(); ++i) {
        for (int j = 0; j < tmp.height(); ++j) {
            QColor color = tmp.pixelColor(i, j);
            color.setRed(255 - color.red());
            color.setGreen(255 - color.green());
            color.setBlue(255 - color.blue());
            tmp.setPixelColor(i, j, color);
        }
    }
    QIcon icon{QPixmap::fromImage(tmp)};
    m_trayIcon->setIcon(icon);

    if (m_mainWindow) {
        m_mainWindow->setWindowIcon(icon);
        m_mainWindow->updatePage(data);
    }
}

void MainProcess::freeMemory() {
    setMainWindowEnabled(false);
}

void MainProcess::setMainWindowEnabled(bool state) {
    bool cache = false;
    if (state) {
        if (!m_mainWindow) {
            qDebug() << "Allocate new MainWindow.";
            m_mainWindow = new MainWindow();
            m_mainWindow->injectTianqiAccesser(m_tianqiAccesser);
            connect(m_mainWindow->get_toolButton_refresh(), &QToolButton::clicked, m_refreshAction, &QAction::trigger);
            connect(m_mainWindow->get_toolButton_settings(), &QToolButton::clicked, m_settingsShowAction,
                    &QAction::trigger);
            updatePage();
            cache = true;
        }
    } else {
        if (m_mainWindow) {
            if (m_mainWindow->isVisible()) {
                cache = true;
            } else {
                qDebug() << "Delete MainWindow.";
                disconnect(m_mainWindow->get_toolButton_refresh(), &QToolButton::clicked, m_refreshAction,
                           &QAction::trigger);
                disconnect(m_mainWindow->get_toolButton_settings(), &QToolButton::clicked, m_settingsShowAction,
                           &QAction::trigger);
                m_mainWindow->deleteLater();
                m_mainWindow = nullptr;
            }
        }
    }
    if (cache) m_tianqiAccesser->restartCaching();
}

void MainProcess::showMainWindow() {
    setMainWindowEnabled(true);
    m_mainWindow->showPageMain();
}

void MainProcess::showSettingsDialog() {
    setMainWindowEnabled(true);
    m_mainWindow->showPageSettings();
}

void MainProcess::iconActivated(QSystemTrayIcon::ActivationReason reason) {
    if (reason == QSystemTrayIcon::Trigger) {
        setMainWindowEnabled(true);
        if (m_mainWindow->isVisible()) m_mainWindow->close();
        else showMainWindow();
    }
}
